<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/30
 * Time: 17:39
 */
namespace app\api\common;
use Des3\DES3;
use think\Controller;
use think\Db;
use think\Exception;
use Ucpaas\Ucpaas;

class Common extends Controller
{
    protected static $err_code = 0;

    /**
     *
     * @apiGroup Common
     * @apiVersion 1.0.1
     * @apiDescription 发送短信
     * @api {post} /common.send_note 发送短信
     * @apiName Common_send_note
     * @apiParam {String} phone 用户手机号码(DES3)加密
     * @apiParam {int} type 短信类型: 1.验证码 2.找回密码
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function send_note($param)
    {
        if (!isset($param['phone']) || !isset($param['type']))
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        //启动事物
        Db::startTrans();
        try
        {
            $des = new DES3();
            $param['phone'] = $des->decrypt($param['phone']);
            /* 调用验证器 验证数据 */
            $validate = validate('api/Common');
            if (!$validate->scene('check_phone')->check(['phone' => $param['phone']]))
            {
                self::$err_code = $validate->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }
            if ($param['type'] == 1){
                $is_existence = Db::table('yf_member')->field('id')->where('phone',$param['phone'])->find();
                if ($is_existence){
                    self::$err_code = 400020;
                    throw new Exception(config('error_code.'.self::$err_code));
                }
            }else if ($param['type'] == 2){
                $is_existence = Db::table('yf_member')->field('id')->where('phone',$param['phone'])->find();
                if (!$is_existence){
                    self::$err_code = 400031;
                    throw new Exception(config('error_code.'.self::$err_code));
                }
            }
            $begin_time = strtotime(date('Y-m-d',time()));
            $end_time = $begin_time + 86400;
            $send_num = Db::table('yf_note_code')->where('add_time','between',[$begin_time,$end_time])->where(['phone'=>$param['phone'],'status'=>0])->count();
            if ($send_num >10){
                self::$err_code = 0;
                throw new Exception('未验证的短信超过使用限额10');
            }
            $templateid = 0;
            if ($param['type'] == 1){
                $templateid = '286208';
            }else if ($param['type'] == 2){
                $templateid = '289821';
            }else if ($param['type'] == 3){
                $templateid = '289821';
            }
            //初始化必填
            //填写在开发者控制台首页上的Account Sid
            $options['accountsid'] = config('sms.AccountSid');
            //填写在开发者控制台首页上的Auth Token
            $options['token'] = config('sms.Token');
            $ucpass = new Ucpaas($options);
            $appid = config('sms.appid');	//应用的ID，可在开发者控制台内的短信产品下查看
            if ($param['phone'] == '13312345678'){
                $code = 8857;
                $mobile = $param['phone'];
                //70字内（含70字）计一条，超过70字，按67字/条计费，超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
                Db::table('yf_note_code')->insertGetId(['code' => $code, 'add_time' => time(), 'phone' => $mobile, 'type' => $param['type']]);
            }else{
                $code = rand(1000, 9999);
                $par = $code.','.'3'; //多个参数使用英文逗号隔开（如：param=“a,b,c”），如为参数则留空
                $mobile = $param['phone'];
                //70字内（含70字）计一条，超过70字，按67字/条计费，超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
                Db::table('yf_note_code')->insertGetId(['code' => $code, 'add_time' => time(), 'phone' => $mobile, 'type' => $param['type']]);
                $data = $ucpass->SendSms($appid,$templateid,$par,$mobile,'');
                $arr_data = json_decode($data,true);
                if ($arr_data['code'] != '000000'){
                    self::$err_code = 400021;
                    throw new Exception(config('error_code.'.self::$err_code));
                }
            }
//            if ($_SERVER['HTTP_HOST'] == 'api.huisangjiang.com'){
//                $code = rand(1000, 9999);
//                $par = $code.','.'3'; //多个参数使用英文逗号隔开（如：param=“a,b,c”），如为参数则留空
//                $mobile = $param['phone'];
//                //70字内（含70字）计一条，超过70字，按67字/条计费，超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
//                Db::table('yf_note_code')->insertGetId(['code' => $code, 'add_time' => time(), 'phone' => $mobile, 'type' => $param['type']]);
//                $data = $ucpass->SendSms($appid,$templateid,$par,$mobile,'');
//                $arr_data = json_decode($data,true);
//                if ($arr_data['code'] != '000000'){
//                    self::$err_code = 400021;
//                    throw new Exception(config('error_code.'.self::$err_code));
//                }
//            }else{
//                $code = 8888;
//                $mobile = $param['phone'];
//                //70字内（含70字）计一条，超过70字，按67字/条计费，超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
//                Db::table('yf_note_code')->insertGetId(['code' => $code, 'add_time' => time(), 'phone' => $mobile, 'type' => $param['type']]);
//            }
            // 回滚事务
            Db::commit();
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Common
     * @apiVersion 1.0.1
     * @apiDescription 获取物流公司代码
     * @api {post} /common.express_code 获取物流公司代码
     * @apiName Common_express_code
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.express_id  物流id
     * @apiSuccess {int} data.express_name  物流名称
     * @apiSuccess {int} data.express_code  物流公司代码
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function express_code($param)
    {
        try
        {
            $express_list = db('express')->field('express_id,express_name,express_code')->order('sort desc')->select();
            return ['code' => 200, 'data'=>$express_list,'msg' => 'SUCCESS'];
        } catch (Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Common
     * @apiVersion 1.0.1
     * @apiDescription 轮播
     * @api {post} /common.banner 轮播
     * @apiName Common_banner
     * @apiParam {int} position 轮播位置 1 首页顶部 2 首页中部 3好货页面
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 轮播数据
     * @apiSuccess {int} data.carousel_id  轮播id
     * @apiSuccess {String} data.title  标题
     * @apiSuccess {int} data.cate  类型 1店铺 2网址链接 3专题 4单个商品
     * @apiSuccess {String} data.item_content
     * @apiSuccess {String} data.couponurl  cate=4时，才有用，其他类型没用
     * @apiSuccess {String} data.image_url  封面图
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function banner($param){
        if (!isset($param['position'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try{
            if (isset($param['shop_id'])){
                $where['shop_id'] = $param['shop_id'];
            }else{
                $where['shop_id'] =0;
            }
            $where['status'] =1;
            $where['start_time'] =['lt',time()];
            $where['end_time'] =['gt',time()];
            $where['position'] =$param['position'];
            $banner_list = db('carousel')->field('carousel_id,title,cate,item_content,couponurl,image image_url')->where($where)->order('sort asc')->select();
            if ($banner_list){
                foreach ($banner_list as $k=>$v){
                    $banner_list[$k]['image_url'] = get_img_url($v['image_url']);
                }
            }else{
                $banner_list = [];
            }
            return ['data' =>$banner_list, 'code' => 200, 'msg' => 'success'];
        }catch (Exception $e){
            return ['data' =>'', 'code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Common
     * @apiVersion 1.0.1
     * @apiDescription 绑定手机
     * @api {post} /Common.phone_band 绑定手机
     * @apiName Common_phone_band
     * @apiParam {int} position 轮播位置 1 首页顶部 2 首页中部 3好货页面
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 轮播数据
     * @apiSuccess {int} data.carousel_id  轮播id
     * @apiSuccess {String} data.title  标题
     * @apiSuccess {int} data.cate  类型 1店铺 2网址链接 3专题 4单个商品
     * @apiSuccess {String} data.item_content
     * @apiSuccess {String} data.couponurl  cate=4时，才有用，其他类型没用
     * @apiSuccess {String} data.image_url  封面图
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function phone_band($param){

        if (!isset($param['position'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $banner_list = db('carousel')->field('carousel_id,title,cate,item_content,couponurl,image image_url')->where(['status'=>1,'start_time'=>['lt',time()],'end_time'=>['gt',time()],'position'=>$param['position']])->order('sort asc')->select();
            if ($banner_list){
                foreach ($banner_list as $k=>$v){
                    $banner_list[$k]['image_url'] = get_img_url($v['image_url']);
                }
            }else{
                $banner_list = [];
            }
            return ['data' =>$banner_list, 'code' => 200, 'msg' => 'success'];
        }catch (Exception $e){
            return ['data' =>'', 'code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }
}